<?php
/**购物车表模型
 * @Author: 976123967@qq.com
 * @Date:   2014-09-08 22:02:27
 * @Last Modified by:   chen
 * @Last Modified time: 2014-09-08 23:35:23
 */
class CartModel extends Model{


	public $table ='cart';

	/**
	 * [get_cart_count 统计购物车商品种数]
	 * @return [type] [description]
	 */
	public function get_cart_count()
	{


		// 能到执行到这里购物车中肯定有商品

		//没有登录
		if(!isset($_SESSION['uid']))
		{
			return count($_SESSION['cart']['goods']);
		}
		//登录了
		else
		{
			return $this->where(array('user_id'=>session('uid')))->count();
		}
	}


	/**
	 * [get_cart_all 购物车列表]
	 * @return [type] [description]
	 */
	public function get_cart_all()
	{
		$cart = array();
		$model = K('Goods');
		//没有登录
		if(!isset($_SESSION['uid']))
		{
			// 购物车空
			if(!isset($_SESSION['cart'])) return false;

			// 获取商品信息
			foreach($_SESSION['cart']['goods'] as $k=>$v)
			{
				$goods = $model->get_goods_one($v['id']);
				// 数量
				$goods['num'] = $v['num'];	
				$cart[] = $goods;
			}
		}
		// 已经登录
		else
		{
			
			$data =  $this->where(array('user_id'=>session('uid')))->all();
			// 购物车空
			if(!$data) return false;
			// 获取商品信息
			foreach($data as $k=>$v)
			{
				$goods = $model->get_goods_one($v['goods_id']);
				// 数量
				$goods['num'] = $v['goods_num'];	
				$cart[] = $goods;
			}
		}
		return $cart;
	}


	/**
	 * [get_cart_format 统计购物车信息]
	 * @return [type] [description]
	 */
	public function get_cart_format()
	{
		$cart = $this->get_cart_all();
		$totalPrice = 0;
		// 购物车空
		if(!$cart) return array('totalPrice'=>$totalPrice,'cart'=>$cart);
		foreach($cart as $k=>$v)
		{
			$cart[$k]['subtotal'] = $v['num'] * $v['price'];
			$totalPrice += $cart[$k]['subtotal'];
		}

		return array('totalPrice'=>$totalPrice,'cart'=>$cart);
	}



	/**
	 * [add_cart 已经登录后添加购物车]
	 * @param [type] $data [description]
	 */
	public function add_cart($data)
	{
		$where = array('user_id'=>$data['user_id'],'goods_id'=>$data['goods_id']);
		// 检查是否存在
		// 存在更新数量
		if($cartId=$this->where($where)->getField('cart_id'))
		{
			$this->inc('goods_num','cart_id='.$cartId,$data['goods_num']);
		}
		// 不存在添加信息
		else
		{
			$this->add($data);
		}
		return  $cartId;
	}


	/**
	 * [move_to_cart 登录后把session里的购物车信息更新到数据库]
	 * @return [type] [description]
	 */
	public function move_to_cart()
	{
		if(isset($_SESSION['cart']))
		{
			foreach ($_SESSION['cart']['goods'] as $k => $v) 
			{
				$data  = array(
					'goods_id'=>$v['id'],
					'goods_num'=>$v['num'],
					'user_id'=>session('uid')
				);
				$this->add_cart($data);
			}
			// 删除session
			unset($_SESSION['cart']);
		}
	}


}